/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.file.storage.local;

import java.io.File;
import java.io.IOException;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import com.foreveross.bsl.file.storage.FileStorage;
import com.foreveross.bsl.file.storage.FileStorageFactory;


/**
 * xxx
 * 
 * @author Wangyi
 * @version v1.0
 * 
 * @date 2013-9-12
 * 
 */
public class LocalFileStorageFactory extends FileStorageFactory {
	
	private final static Logger log = LoggerFactory.getLogger(LocalFileStorageFactory.class);
	
	private final static String OS_NAME=System.getProperties().getProperty("os.name").toUpperCase();
	private final static String DEFAULT_HOME_PATH_NAME="bsl_home"+File.separatorChar+"uploads";

	private String homePath;

	public LocalFileStorageFactory() {
		this.homePath=this.getDefaultHomePath();
	}
	
	public static LocalFileStorageFactory createByConfig(){
		return createByConfig("classpath:/filestorage/local.properties");
	}
	
	public static LocalFileStorageFactory createByConfig(String location){
		LocalFileStorageFactory storageFactory=new LocalFileStorageFactory();
		ResourceLoader resLoader=new DefaultResourceLoader();
		Resource res=resLoader.getResource(location);
		if(res.exists()){
			Properties props=new Properties();
			try {
				log.debug("load local filestorage config: {}", res.getURL());
				props.load(res.getInputStream());
				String homePath=props.getProperty("local.homepath");
				if(!StringUtils.isEmpty(homePath)){
					storageFactory.setHomePath(homePath);
				}
			} catch (IOException e) {
				log.error(e.getMessage());
			}
		}
		return storageFactory;
	}

	/**
	 * 判断当前操作系统是不是window
	 * 
	 * @return boolean
	 */
	public static boolean isWindows() {
		boolean flag = false;
		if (OS_NAME.indexOf("WINDOWS") != -1) {
			flag = true;
		}
		return flag;
	}
	
	private String getDefaultHomePath(){
		String defaultHomePath;
		if(isWindows()){
			defaultHomePath="C:\\"+DEFAULT_HOME_PATH_NAME;
		}
		else{
			defaultHomePath="/"+DEFAULT_HOME_PATH_NAME;
		}
		return defaultHomePath;
	}

	@Override
	public FileStorage getFileStorage() {
		return new LocalFileStorage(new File(this.homePath));
	}

	/**
	 * @return the homePath
	 */
	public String getHomePath() {
		return homePath;
	}

	/**
	 * @param homePath the homePath to set
	 */
	public void setHomePath(String homePath) {
		this.homePath = homePath;
	}

}
